import skfuzzy as fuzz
import numpy as np
import re
import base64
import requests
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.collections as mcoll
import base64
import requests
import re
from datetime import datetime

from datetime import datetime
from bs4 import BeautifulSoup
from pylab import mpl
from skfuzzy import control as ctrl

# 设置中文显示字体
mpl.rcParams["font.sans-serif"] = ["SimHei"]
mpl.rcParams["axes.unicode_minus"] = False

defaultExpecetedTime=17             #默认个人理想运动时间
defaultExpectedTemperature=25      #默认个人最适温度
defaultAcceptableAirquality=80     #默认个人可以接受的空气质量指数

expecetedTime=defaultExpecetedTime             #个人理想运动时间
expectedTemperature=defaultExpectedTemperature      #个人最适温度
acceptableAirquality=defaultAcceptableAirquality     #个人可以接受的空气质量指数


#获取天气状况
class Get_data:

    @staticmethod
    def get_air_quality():
        cookies = {
            'BAIDU_SSP_lcr': 'https://cn.bing.com/',
            'Hm_lvt_a3f2879f6b3620a363bec646b7a8bcdd': '1735031818',
            'HMACCOUNT': '5DEB94B3FE2658CB',
            'lastCountyId': '71872',
            'lastCountyTime': '1735031949',
            'lastCountyPinyin': 'shushan',
            'lastProvinceId': '10',
            'lastCityId': '58321',
            'Hm_lpvt_a3f2879f6b3620a363bec646b7a8bcdd': '1735031950',
        }
        headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'cache-control': 'no-cache',
            # 'cookie': 'BAIDU_SSP_lcr=https://cn.bing.com/; Hm_lvt_a3f2879f6b3620a363bec646b7a8bcdd=1735031818; HMACCOUNT=5DEB94B3FE2658CB; lastCountyId=71872; lastCountyTime=1735031949; lastCountyPinyin=shushan; lastProvinceId=10; lastCityId=58321; Hm_lpvt_a3f2879f6b3620a363bec646b7a8bcdd=1735031950',
            'pragma': 'no-cache',
            'priority': 'u=0, i',
            'referer': 'https://tianqi.2345.com/air-71142.htm',
            'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'document',
            'sec-fetch-mode': 'navigate',
            'sec-fetch-site': 'same-origin',
            'sec-fetch-user': '?1',
            'upgrade-insecure-requests': '1',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
        }
        response = requests.get('https://tianqi.2345.com/air-71872.htm', cookies=cookies, headers=headers)
        obj1 = re.compile(r'.*?hoursData48 = \[(?P<data>.*?)\];', re.S)
        obj2 = re.compile(r'.*?hoursData24 = \[(?P<data>.*?)\];', re.S)
        data1 = obj1.match(response.text).group('data')
        data2 = obj2.match(response.text).group('data')
        time1= list(map(int,[i.strip('"') for i in data1.split(',')]))
        time2= list(map(int,[i.strip('"') for i in data2.split(',')]))
        # 获取当前时间
        current_time = datetime.now()
        # 获取当前时间的小时数
        current_hour = int(current_time.hour)
        data=time2[len(time2)-current_hour:]+time1[:24-current_hour]
        return data

    @staticmethod
    def get_weather():
        data1_list = []

        cookies = {
            'Hm_lvt_aadbcc83cc37610f46f503983c444e90': '1734753822,1734831165',
            'Hm_lpvt_aadbcc83cc37610f46f503983c444e90': '1734831165',
            'HMACCOUNT': '5DEB94B3FE2658CB',
            'Hm_lvt_0b8b0a2a4a45cbaaa6f549dcad3329a6': '1734753823,1734831165',
            'Hm_lpvt_0b8b0a2a4a45cbaaa6f549dcad3329a6': '1734831165',
        }
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            # 'Content-Length': '0',
            # 'Cookie': 'Hm_lvt_aadbcc83cc37610f46f503983c444e90=1734753822,1734831165; Hm_lpvt_aadbcc83cc37610f46f503983c444e90=1734831165; HMACCOUNT=5DEB94B3FE2658CB; Hm_lvt_0b8b0a2a4a45cbaaa6f549dcad3329a6=1734753823,1734831165; Hm_lpvt_0b8b0a2a4a45cbaaa6f549dcad3329a6=1734831165',
            'Origin': 'https://air.cnemc.cn:18007',
            'Pragma': 'no-cache',
            'Referer': 'https://air.cnemc.cn:18007/',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0',
            'X-Requested-With': 'XMLHttpRequest',
            'sec-ch-ua': '"Microsoft Edge";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        loc = '{"l":"合肥市","r":"安徽省","c":"中华人民共和国","i":"cn","t":102,"g":"zh-cn","x":"117.2271506","y":"31.8204307"}'
        params = {
            'ocid': 'ansmsnweather',
            'loc': base64.b64encode(loc.encode('utf-8')),
            'weadegreetype': 'C',
        }
        resp2 = requests.get(
            'https://www.msn.cn/zh-cn/weather/forecast/in-%E5%AE%89%E5%BE%BD%E7%9C%81,%E5%90%88%E8%82%A5%E5%B8%82?ocid=ansmsnweather&loc=eyJsIjoi6JyA5bGx5Yy6IiwiciI6IuWuieW%2BveecgSIsInIyIjoi5ZCI6IKl5biCIiwiYyI6IuS4reWNjuS6uuawkeWFseWSjOWbvSIsImkiOiJDTiIsImciOiJ6aC1jbiIsIngiOiIxMTcuMTY4IiwieSI6IjMxLjgzMSJ9&weadegreetype=C',
            params=params,
            cookies=cookies,
            headers=headers
        )

        f = open('2.txt', 'w', encoding='utf-8')
        f.write(resp2.text)
        txt = resp2.text

        obj1 = re.compile(r'.*?currentCondition.*?currentRaw.*?forecast.*?"hourly":(?P<data>.*?)"raToMN', re.S)
        res = obj1.match(txt).group('data')
        obj2 = re.compile(r'"cap":(?P<cap>.*?),', re.S)
        obj3 = re.compile(r'"temperature":(?P<temperature>.*?),', re.S)
        obj4 = re.compile(r'"pvdrWindSpd":(?P<pvdrWindSpd>.*?),', re.S)

        cap = obj2.findall(res)
        temperature = obj3.findall(res)
        pvdrWindSpd = obj4.findall(res)

        for i in range(len(cap)):
            p=pvdrWindSpd[i].strip('"')
            p=p if p != "微风" else "1级"
            data1_list.append([cap[i].strip('"'), temperature[i], p.strip('"').strip('级')])

        resp = requests.get("https://lishidata.com/area/%E5%AE%89%E5%BE%BD/%E5%90%88%E8%82%A5.html")
        obj1 = re.compile(r'<td class="text-center">(?P<data>.*?)</td>')
        datas = obj1.findall(resp.text)

        data2_list=[]
        lists=[]
        k = 0
        for i in datas:
            if ((k) % 12 == 0):
                data2_list.append(lists)
                lists = []
                k = 0
            if (k == 2):
                lists.append(i.strip('"'))
            if (k == 3):
                lists.append(i.strip("℃"))
            if (k == 6):
                lists.append(i.strip().strip('级'))
            k = k + 1
        data2_list = [i for i in data2_list if i != []]

        data_list=data1_list[::-1]+data2_list[:24-len(data1_list)]
        return data_list[::-1]


def GetApi():
    res_air = Get_data.get_air_quality()
    res_wether = Get_data.get_weather()

    # 由1到24点构成
    # 结构由时间,天气，温度，风速，空气质量构成
    res = []
    for i in range(24):
        l = [i]+res_wether[i]
        l.append(res_air[i])
        res.append(l)
    return res



#时间避免的隶属度函数
def MembershipFunOfCurTime_Avoid(time_array):
    membership = np.zeros_like(time_array)
    # 定义梯形参数列表
    global expecetedTime

    trap_params =None
    if expecetedTime<=12:
        trap_params = [
            [0, 0, 0.71*expecetedTime, expecetedTime],
            [21.5, 23, 24, 24]
        ]
    else:
        trap_params = [
            [0, 0, 5, 7],
            [1.26*expecetedTime, 1.35*expecetedTime, 48, 48]
        ]

    for a, b, c, d in trap_params:
        temp_membership = np.zeros_like(time_array)
        mask_b_to_c = (time_array >= b) & (time_array <= c)
        temp_membership[mask_b_to_c] = 1

        mask_a_to_b = (time_array >= a) & (time_array < b)
        temp_membership[mask_a_to_b] = (time_array[mask_a_to_b] - a) / (b - a)

        mask_c_to_d = (time_array > c) & (time_array <= d)
        temp_membership[mask_c_to_d] = (d - time_array[mask_c_to_d]) / (d - c)

        membership = np.maximum(membership, temp_membership)

    return membership

#时间考虑的隶属度函数
def MembershipFunOfCurTime_Consider(time_array):
    membership = np.zeros_like(time_array)
    # 定义梯形参数列表
    global expecetedTime
    trap_params = None
    if expecetedTime<=12:
        trap_params = [
            [16, 20, 21, 22],
            [1.57*expecetedTime, 1.7*expecetedTime, 2*expecetedTime, 2.15*expecetedTime]
        ]
    else:
        trap_params = [
            [0.94*expecetedTime, 1.17*expecetedTime, 1.23*expecetedTime, 1.46*expecetedTime],
            [11, 12, 14, 15]
        ]
    for a, b, c, d in trap_params:
        temp_membership = np.zeros_like(time_array)
        mask_b_to_c = (time_array >= b) & (time_array <= c)
        temp_membership[mask_b_to_c] = 1

        mask_a_to_b = (time_array >= a) & (time_array < b)
        temp_membership[mask_a_to_b] = (time_array[mask_a_to_b] - a) / (b - a)

        mask_c_to_d = (time_array > c) & (time_array <= d)
        temp_membership[mask_c_to_d] = (d - time_array[mask_c_to_d]) / (d - c)

        membership = np.maximum(membership, temp_membership)

    return membership

#时间推荐的隶属度函数
def MembershipFunOfCurTime_Recommendation(time_array):
    membership = np.zeros_like(time_array)

    # 定义梯形参数列表
    trap_params = None
    global expecetedTime
    if expecetedTime<=12:
        trap_params = [
            [0.86 * expecetedTime, expecetedTime, 1.57 * expecetedTime, 1.7 * expecetedTime],
            [15, 16, 17, 19]
        ]
    else:
        trap_params = [
            [6, 7, 11, 12],
            [0.88*expecetedTime, 0.94*expecetedTime, expecetedTime, 1.1*expecetedTime]
        ]

    for a, b, c, d in trap_params:
        temp_membership = np.zeros_like(time_array)
        mask_b_to_c = (time_array >= b) & (time_array <= c)
        temp_membership[mask_b_to_c] = 1

        mask_a_to_b = (time_array >= a) & (time_array < b)
        temp_membership[mask_a_to_b] = (time_array[mask_a_to_b] - a) / (b - a)

        mask_c_to_d = (time_array > c) & (time_array <= d)
        temp_membership[mask_c_to_d] = (d - time_array[mask_c_to_d]) / (d - c)

        membership = np.maximum(membership, temp_membership)

    return membership

weatherSet = {
    '晴朗': 0,
    '晴': 2,
    '局部晴朗': 1,
    '大部晴朗': 1,
    '局部多云': 2,
    '多云': 3,
    '阴': 4,
    '雾霾':5,
    '霾':5,
    '雾': 5,
    '未知':6,
}

#将天气映射到数值上
def GetWeatherLevel(weather):
    for key in weatherSet:
        if key  == weather:
            return weatherSet.get(weather, None)
    return 9


#生成模糊推理机器
def GetFuzzyInferenceSystem():
# ----------------------（一）定义输入输出
    # 定义输入变量:空气质量、风级、温度、当前时间、天气状况（阴、晴朗、多云...）
    airQuality=ctrl.Antecedent(np.linspace(0, 500, 501), '空气质量指数')
    wind=ctrl.Antecedent(np.linspace(0, 20, 21), '风级')
    temperature=ctrl.Antecedent(np.linspace(-50, 50, 101), '温度')
    curTime=ctrl.Antecedent(np.linspace(0, 24, 240), '时间')
    weather=ctrl.Antecedent(np.linspace(0, 10, 100), '天气')

    # 定义输出：适宜度，范围为[0,10]，越大适宜度越高
    suit = ctrl.Consequent(np.linspace(0, 10, 500), '适宜度')

    global expecetedTime
    global expectedTemperature
    global acceptableAirquality
    expectedTemperature+=50
# ----------------------（二）确定输入输出的隶属度函数
    # 为输入和输出变量分配隶属度函数
    #空气质量指数的隶属函数为梯形函数
    airQuality['优']=fuzz.trapmf(airQuality.universe, [0,0,acceptableAirquality/2,0.75*acceptableAirquality])
    airQuality['良']=fuzz.trapmf(airQuality.universe, [acceptableAirquality/2,0.75*acceptableAirquality,1.15*acceptableAirquality,1.4*acceptableAirquality])
    airQuality['轻度污染']=fuzz.trapmf(airQuality.universe, [1.15*acceptableAirquality,1.4*acceptableAirquality,1.75*acceptableAirquality,2*acceptableAirquality])
    airQuality['中度污染']=fuzz.trapmf(airQuality.universe, [1.75*acceptableAirquality,2*acceptableAirquality,2.4*acceptableAirquality,2.9*acceptableAirquality])
    airQuality['重度污染']=fuzz.trapmf(airQuality.universe, [2.4*acceptableAirquality,2.9*acceptableAirquality,3.5*acceptableAirquality,4*acceptableAirquality])
    airQuality['严重污染']=fuzz.trapmf(airQuality.universe, [3.5*acceptableAirquality,4*acceptableAirquality,500*acceptableAirquality,500*acceptableAirquality])


    #温度的隶属函数为三角函数，开始和结束部分使用梯形函数
    temperature['寒冷'] = fuzz.trapmf(temperature.universe, [-50, -50, -50+0.32*expectedTemperature, -50+0.73*expectedTemperature])
    temperature['凉'] = fuzz.trimf(temperature.universe, [-50+0.67*expectedTemperature, -50+0.8*expectedTemperature, -50+0.9*expectedTemperature])
    temperature['温和'] = fuzz.trimf(temperature.universe, [-50+0.87*expectedTemperature, -50+0.93*expectedTemperature, -50+expectedTemperature])
    temperature['温暖'] = fuzz.trimf(temperature.universe, [-50+0.93*expectedTemperature, -50+1.05*expectedTemperature, -50+1.14*expectedTemperature])
    temperature['炎热'] = fuzz.trapmf(temperature.universe, [-50+1.06*expectedTemperature, -50+1.23*expectedTemperature, 150, 150])


    #温度的隶属函数为三角函数，结束部分使用梯形函数
    wind['静风'] = fuzz.trimf(wind.universe, [0, 0, 2])
    wind['微风'] = fuzz.trimf(wind.universe, [1, 3, 5])
    wind['劲风'] = fuzz.trimf(wind.universe, [4, 6, 8])
    wind['狂风'] = fuzz.trapmf(wind.universe, [7, 9,20,20])

    #时间的隶属度函数为自定义的梯形函数
    curTime['推荐']=MembershipFunOfCurTime_Recommendation(curTime.universe)
    curTime['考虑']=MembershipFunOfCurTime_Consider(curTime.universe)
    curTime['避免']=MembershipFunOfCurTime_Avoid(curTime.universe)

    #天气的隶属度函数为三角函数
    weather['极好'] = fuzz.trimf(weather.universe, [0, 0, 2])
    weather['较好'] = fuzz.trimf(weather.universe, [1, 3, 4])
    weather['一般'] = fuzz.trimf(weather.universe, [3, 5, 7])
    weather['极差'] = fuzz.trimf(weather.universe, [6, 10, 10])

    #输出适宜度的隶属函数为三角函数，开始和结束部分使用梯形函数
    suit['强烈建议户外运动'] = fuzz.trapmf(suit.universe, [8,9,10,10])
    suit['建议户外运动'] = fuzz.trimf(suit.universe, [7,8,9])
    suit['可以考虑户外运动'] = fuzz.trimf(suit.universe, [5,6,8])
    suit['建议尽量避免户外运动'] = fuzz.trimf(suit.universe, [2,4,6])
    suit['建议避免户外运动'] = fuzz.trapmf(suit.universe, [0,0,2,3])

# ----------------------（三）添加模糊规则
    rule1 = ctrl.Rule(airQuality['优']&curTime['推荐']&weather['极好'],suit['强烈建议户外运动'])
    rule2 = ctrl.Rule(weather['一般']& temperature['温和']&curTime['推荐'],suit['建议户外运动'])
    rule3 = ctrl.Rule(airQuality['轻度污染'] & weather['一般'], suit['可以考虑户外运动'])
    rule4 = ctrl.Rule(temperature['寒冷'],suit['建议尽量避免户外运动'])
    rule5 = ctrl.Rule(airQuality['重度污染'],suit['建议尽量避免户外运动'])
    rule6 = ctrl.Rule(airQuality['严重污染'],suit['建议避免户外运动'])
    rule7 = ctrl.Rule(temperature['寒冷'],suit['建议避免户外运动'])
    rule8 = ctrl.Rule(wind['狂风'],suit['建议避免户外运动'])
    rule9 = ctrl.Rule(curTime['避免'],   suit['建议避免户外运动'])
    rule10 = ctrl.Rule(weather['极差'],suit['建议避免户外运动'])
    rule11 = ctrl.Rule(temperature['炎热'],suit['建议尽量避免户外运动'])
    rule12=ctrl.Rule(weather['一般']&wind['微风'],suit['建议户外运动'])
    rule13 = ctrl.Rule(airQuality['良']  & curTime['推荐'] & weather['极好'],suit['建议户外运动'])
    rule14 = ctrl.Rule(temperature['凉']&weather['极好'],suit['可以考虑户外运动'])
    rule15 = ctrl.Rule(temperature['温暖']& curTime['推荐'],suit['建议户外运动'])
    rule16 = ctrl.Rule(wind['劲风'],suit['建议尽量避免户外运动'])
    rule17 = ctrl.Rule(curTime['考虑'],suit['可以考虑户外运动'])
    rule18 = ctrl.Rule(curTime['推荐']&weather['较好'],suit['建议户外运动'])

    running_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7,rule8,  rule9, rule10,rule11,rule12,rule13,rule14,rule15, rule16, rule17, rule18])

    airQuality.view()
    temperature.view()
    wind.view()
    curTime.view()
    weather.view()
    suit.view()

    return ctrl.ControlSystemSimulation(running_ctrl)


#启动函数
running_simulation=None
def LuanchFuzzyInferenceSystem():
    global running_simulation
    running_simulation= GetFuzzyInferenceSystem()

#模糊推理函数
# ----------------------（四）模糊推理
def GetSuit(argAirQuality, argTemperature, argWind, argWeather, argCurTime):
    global running_simulation
    running_simulation.input['空气质量指数'] = argAirQuality
    running_simulation.input['温度'] = argTemperature
    running_simulation.input['风级'] = argWind
    running_simulation.input['时间'] = argCurTime
    running_simulation.input['天气'] = argWeather
    running_simulation.compute()
# ----------------------（五）去模糊化
    return running_simulation.output['适宜度']


#根据适宜度给出建议
def GetAdviceBySuit(nsuit):
    if 0<=nsuit<2:
        print("建议避免户外运动")
    elif 2<=nsuit<5:
        print("建议尽量避免户外运动")
    elif 5<=nsuit<7:
        print("可以考虑户外运动")
    elif 7<=nsuit<9:
        print("建议户外运动")
    elif 9<=nsuit:
        print("强烈建议户外运动")

#获取当前时间
def GetTime():
    now = datetime.now()
    hours = now.hour
    minutes = now.minute
    return hours+minutes/60

#获取个性化数据
def GetPersonalizationInput():
    global expecetedTime
    global expectedTemperature
    global acceptableAirquality
    expecetedTime=float(input('个人一天中最适合运动的时间:[0,24]'))
    expectedTemperature=float(input('个人最适体感温度:摄氏度[-50,50]'))
    acceptableAirquality=int(input('个人可以接受的最差空气质量指数:[0,500]'))
    if expectedTemperature<-50:
        expectedTemperature=-50
    elif expectedTemperature>50:
        expectedTemperature=50
    if expecetedTime<0:
        expecetedTime=0
    elif expecetedTime>24:
        expecetedTime=24
    if acceptableAirquality<0:
        acceptableAirquality=0
    elif acceptableAirquality>500:
        acceptableAirquality=500
    return expecetedTime,expectedTemperature,acceptableAirquality

#获取输入函数
def GetInput():
    ret=GetApi()
    argAirQuality,argTemperature,argWind,argWeather=[],[],[],[]
    for i in ret:
        argAirQuality.append(i[4])
        argTemperature.append(i[2])
        argWind.append(i[3])
        argWeather.append(i[1])
    argAirQuality=[int(float(num)+0.5) for num in argAirQuality]
    argTemperature = [int(float(num)+0.5) for num in argTemperature]
    argWind = [int(float(num)+0.5) for num in argWind]

    #绘图
    plt.figure()
    x = np.arange(0, 24)
    plt.plot(x, argTemperature, 'o-', markerfacecolor='none', markeredgecolor='blue', markersize=2, linewidth=1)
    plt.title('今日温度变化')
    plt.xlabel('时间（小时）')
    plt.ylabel('温度')
    plt.grid(color='gray', linestyle='-', linewidth=0.5)
    plt.axvline(x=GetTime(), color='red', linestyle='-', linewidth=1)
    y_text_position = max(argTemperature)
    plt.text(GetTime(), y_text_position, '现在', color='red', ha='center', va='bottom')
    plt.xticks(x)
    plt.show()


    plt.figure()
    x = np.arange(0, 24)  # 横坐标从1到24，代表小时
    plt.plot(x, argAirQuality, 'o-', markerfacecolor='none', markeredgecolor='blue', markersize=2, linewidth=1)
    plt.title('今日空气质量指数变化')
    plt.xlabel('时间（小时）')
    plt.ylabel('空气质量指数')
    plt.grid(color='gray', linestyle='-', linewidth=0.5)
    plt.axvline(x=GetTime(), color='red', linestyle='-', linewidth=1)
    y_text_position = max(argAirQuality)
    plt.text(GetTime(), y_text_position, '现在', color='red', ha='center', va='bottom')
    plt.xticks(x)
    plt.show()


    plt.figure()
    plt.plot(x, argWind, 'o-', markerfacecolor='none', markeredgecolor='blue', markersize=2, linewidth=1)
    plt.title('今日风级变化')
    plt.xlabel('时间（小时）')
    plt.ylabel('风级')
    plt.grid(color='gray', linestyle='-', linewidth=0.5)
    plt.axvline(x=GetTime(), color='red', linestyle='-', linewidth=1)
    y_text_position = max(argWind)
    plt.text(GetTime(), y_text_position, '现在', color='red', ha='center', va='bottom')
    plt.xticks(x)
    plt.show()

    weather_y_pos = {'阴': -0.5, '晴朗': 0, '多云': 0.5, '局部多云': 1.0, '雾霾': -1.0, '局部晴朗': 0.25, '霾': -0.25}
    default_y_pos = 1.5
    hours = np.arange(0, 24)
    fig, ax = plt.subplots()
    ax.set_xlim(-0.5, 23.5)
    ax.set_ylim(-1.5, 2)

    for hour, weather in zip(hours, argWeather):
        y_pos = weather_y_pos.get(weather, default_y_pos)
        ax.text(hour, y_pos, weather, ha='center', va='center', fontsize=12, color='black')

    ax.yaxis.set_ticks([])
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.set_xticks(hours)
    ax.set_xticklabels([f'{h}' for h in hours], rotation=45, ha='right')
    ax.set_title('今日24小时天气状况')
    plt.axvline(x=GetTime(), color='red', linestyle='-', linewidth=1)
    y_text_position = 1
    plt.text(GetTime(), y_text_position, '现在', color='red', ha='center', va='bottom')
    plt.grid(True)
    plt.show()


    target_array = []
    for element in argWeather:
        target_array.append(GetWeatherLevel(element))
    argWeather=target_array

    return argAirQuality, argTemperature, argWind, argWeather


#画出当天一天内的适宜度
def PrintDaySuit():
    argAirQuality, argTemperature, argWind, argWeather = GetInput()
    x = np.arange(0, 24)  # 横坐标从0到23，代表小时
    y = []
    for i in range(24):
        y.append(GetSuit(argAirQuality[i], argTemperature[i], argWind[i], argWeather[i], x[i]))
    num_points = 200
    x_new = np.linspace(x[0], x[-1], num_points)
    y_new = np.interp(x_new, x, y)

    fluorescentGreen = (138 / 255.0, 226 / 255.0, 52 / 255.0, 1)
    emeraldGreen = (0 / 255.0, 255 / 255.0, 0 / 255.0, 1)
    color_thresholds = [2, 5, 7, 9]
    colors = ['red', 'orange', 'yellow', fluorescentGreen, emeraldGreen]
    segments = []

    for i in range(len(x_new) - 1):
        y0 = y_new[i]
        y1 = y_new[i + 1]
        color_index = next((j for j, thresh in enumerate(color_thresholds) if y0 <= thresh), len(colors) - 1)
        segments.append(((x_new[i], y0), (x_new[i + 1], y1), colors[color_index]))


    for segment in segments:
            x0, y0, color = segment[0][0], segment[0][1], segment[2]
            x1, y1 = segment[1][0], segment[1][1]
            plt.plot([x0, x1], [y0, y1], color=color)

    for hour in x:
        plt.axvline(x=hour, color='gray', linestyle='--', linewidth=0.5)


    custom_legend_labels = ['<2: 建议避免户外运动', '2-5: 建议尽量避免户外运动', '5-7: 可以考虑户外运动', '7-9: 建议户外运动 ',
                            '>9: 强烈建议户外运动']
    legend_handles = []

    for i, (threshold_next, color) in enumerate(zip(color_thresholds + [float('inf')], colors)):
        lower_bound = float('-inf') if i == 0 else color_thresholds[i - 1]
        threshold = threshold_next
        upper_bound = threshold if i < len(color_thresholds) else float('inf')
        label = custom_legend_labels[i]
        patch = plt.Rectangle((0, 0), 1, 1, fc=color, label=label)
        legend_handles.append(patch)

    plt.legend(handles=legend_handles, loc='upper center',
               bbox_to_anchor=(0,1),  # 微调图例位置
               borderaxespad=0.,
               prop={'size': 8}  # 缩小字体大小
               )
    plt.axvline(x=GetTime(), color='red', linestyle='-', linewidth=1)
    y_text_position = max(y_new)
    plt.text(GetTime(), y_text_position, '现在', color='red', ha='center', va='bottom')

    plt.xticks(x, [str(i) for i in x])
    plt.plot(x, y, 'o', markerfacecolor='none', markeredgecolor='blue', markersize=2)
    plt.title('今日户外活动适宜度')
    plt.xlabel('时间（小时）')
    plt.ylabel('适宜度')
    plt.grid(True)
    plt.show()



# 重置采用默认配置
def ReSet():
    global expecetedTime
    global expectedTemperature
    global acceptableAirquality
    global defaultExpecetedTime
    global defaultExpectedTemperature
    global defaultAcceptableAirquality
    expecetedTime = defaultExpecetedTime
    expectedTemperature = defaultExpectedTemperature
    acceptableAirquality = defaultAcceptableAirquality
    LuanchFuzzyInferenceSystem()
    PrintDaySuit()

#个性化
def Personalize():
    global personalization
    global expecetedTime
    global expectedTemperature
    global acceptableAirquality
    expecetedTime, expectedTemperature, acceptableAirquality = GetPersonalizationInput()
    LuanchFuzzyInferenceSystem()
    PrintDaySuit()


def Start():
    LuanchFuzzyInferenceSystem()
    PrintDaySuit()
#------------------------------------------调用

Start()
#Personalize()
# ReSet()